Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Networking → Socket Class

Networking

Socket Class

The `java.net.Socket` class in Java provides the fundamental mechanism for network communication using the TCP/IP protocol. It represents one end of a two-way communication link between a client and a server. A `Socket` object is created by a client to connect to a server, and the server accepts the connection, resulting in two `Socket` objects, one on each side, that can send and receive data.

java.net.Socket Methods and Concepts

Constructor: `Socket(InetAddress address, int port)`: This is the most common constructor. `InetAddress` specifies the server's IP address (or hostname), and `port` is the port number the server is listening on. `getInputStream()`: Returns an `InputStream` object, allowing the client to read data sent by the server. `getOutputStream()`: Returns an `OutputStream` object, allowing the client to send data to the server. `close()`: Closes the socket connection, releasing resources. This is crucial to avoid resource leaks; always ensure your sockets are closed properly, ideally using try-with-resources. `getInetAddress()`: Returns the `InetAddress` object of the connected server. `getPort()`: Returns the port number the socket is connected to. `isConnected()`: Checks if the socket is currently connected. `isBound()`: Checks if the socket is bound to a local address and port. `isInputShutdown()`: Checks if input has been shut down. `isOutputShutdown()`: Checks if output has been shut down.

Simple Client-Server Communication

Let's build a basic client-server example to illustrate the usage of the `Socket` class. The server will listen for a connection and echo back any message it receives. The client will connect to the server, send a message, and receive the echoed response.

Server (EchoServer.java):

EchoServer.java import java.io.*; import java.net.*; public class EchoServer { public static void main(String[] args) { try (ServerSocket serverSocket = new ServerSocket(8080)) { // Listen on port 8080 System.out.println("Server started, listening on port 8080"); try (Socket socket = serverSocket.accept(); // Accept a connection BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) { //Autoflush String message; while ((message = in.readLine()) != null) { System.out.println("Received: " + message); out.println("Echo: " + message); // Echo the message back if (message.equalsIgnoreCase("exit")) { break; //Exit condition } } } catch (IOException e) { System.err.println("Error handling client: " + e.getMessage()); } } catch (IOException e) { System.err.println("Error starting server: " + e.getMessage()); } } }

Client (EchoClient.java):

EchoClient.java import java.io.*; import java.net.*; public class EchoClient { public static void main(String[] args) { try (Socket socket = new Socket("localhost", 8080); //Connect to localhost on port 8080 BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) { BufferedReader consoleIn = new BufferedReader(new InputStreamReader(System.in)); String message; while (true) { System.out.print("Enter message (or 'exit' to quit): "); message = consoleIn.readLine(); out.println(message); // Send message to server if (message.equalsIgnoreCase("exit")) { break; } String response = in.readLine(); // Receive server response System.out.println("Server response: " + response); } } catch (IOException e) { System.err.println("Error communicating with server: " + e.getMessage()); } } }

Explanation:

Server: Creates a `ServerSocket` to listen for incoming connections on port 8080. `accept()` blocks until a client connects. It then uses `InputStream` and `OutputStream` to communicate. Client: Creates a `Socket` to connect to the server's address and port. It uses `InputStream` and `OutputStream` to send and receive messages.

Tutorials